import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qx_global_ads/src/cookie_mgr.dart';


import 'ad_type.dart';
import 'response.dart';

class DioClient {
  static final DioClient _instance = DioClient._internal();
  late final Dio dio;
  MyPersistCookieJar? _cookieJar; // 只有在需要时才初始化

  factory DioClient() => _instance;

  DioClient._internal() {
    dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      responseType: ResponseType.json,
    ));
  }

  /// **懒加载 `cookie_jar`，确保应用重启后 `cookie` 仍然可用**
  Future<void> _initCookieJar() async {
    if (_cookieJar == null) {
      final dir = await getApplicationDocumentsDirectory();
      _cookieJar = MyPersistCookieJar(storage: FileStorage('${dir.path}/cookies'));
      dio.interceptors.add(MyCookieManager(_cookieJar!));
      debugPrint("🍪 CookieJar Initialized at: ${dir.path}/cookies");
    }
  }

  /// **自动初始化 `cookie`，并返回 `Dio` 实例**
  Future<Dio> getInstance() async {
    await _initCookieJar();
    return dio;
  }
}




class AdFetcher {

  static const String apiEndpoint = 'https://adv.erushbox.pro/www/delivery/asyncsapp.php?zones=';

  /// **获取广告数据**
  static Future<List<dynamic>> fetchAds(AdType type,{String? zoneId}) async {

    try {
      if (zoneId == null) {
        switch (type) {
          case AdType.banner1:
            zoneId = '1';
            break;
          case AdType.banner2:
            zoneId = '2';
            break;
          case AdType.banner3:
            zoneId = '3';
            break;
          case AdType.banner4:
            zoneId = '4';
            break;
          case AdType.interstitialPortrait:
            zoneId = '5';
            break;
          case AdType.interstitialLandscape:
            zoneId = '6';
            break;
        }
      }

      final String url = '$apiEndpoint$zoneId';
      debugPrint('Fetching ads from: $url');

      Dio dio = await DioClient().getInstance();
      final response = await dio.get(url);

      if (response.statusCode == 200) {
        return response.data is List ? response.data : [];
      } else {
        throw Exception('Failed to fetch banners, Status Code: ${response.statusCode}  Response: ${response.data}');
      }
    } catch (e) {
      debugPrint('❌ Error fetching ads: $e');
      return []; // 返回空列表，避免应用崩溃
    }
  }

  /// **发送日志 URL，不影响主逻辑**
  static Future<void> logUrl(String url) async {
    try {
      Dio dio = await DioClient().getInstance();
      await dio.get(url);
      debugPrint('📝 logUrl sent successfully $url: $url');
    } catch (e) {
      debugPrint('⚠️ Failed to send logUrl $url: $e');
    }
  }


  static Future<num> getAdShowRate(String packageName,{bool isDebug =false}) async {
      var url = "https://advapi.erushbox.pro/ad/config";
      if(isDebug){
        url = "http://192.168.1.28:8090/ad/config";
      }

      try {
         Dio dio = await DioClient().getInstance();
         final response = await dio.get(url,queryParameters:{"packageName":packageName});
         if (response.statusCode == 200) {
           debugPrint('ad show rate: ${response.data}');
           return  response.data['data']['selfAdvertisingRate'] as num;
         }
         return 0;

      } catch (e) {
        debugPrint('❌ Error fetching adsRate: $e');
        return 0;
      }
     
  } 

  static Future<AdAppVo?> getList(String baseUrl, String platform,String packageName,String gameClientId,String sessionId) async {
      var url = "$baseUrl/ad/list";
      try {
         Dio dio = await DioClient().getInstance();
         final response = await dio.get(url,queryParameters:{"platform":platform,"packageName":packageName,"gameClientId":gameClientId,"sessionId":sessionId});
         if (response.statusCode == 200) {
           debugPrint('ad list: ${response.data}');
           if(response.data['code'] != 200 || response.data['data'] == null) return null;
           return AdAppVo.fromJson(response.data['data']);
         }
         return null;
      } catch (e) {
        debugPrint('❌ Error fetching getList: $e');
        return null;
      }
  }

  static Future<AdAppVo?> adComplete(String baseUrl,String platform,String packageName,String gameClientId,String sessionId,String adItemId) async {
      var url = "$baseUrl/ad/complete";
      try {
         Dio dio = await DioClient().getInstance();
         final response = await dio.get(url,queryParameters:{"platform":platform,"packageName":packageName,"gameClientId":gameClientId,"sessionId":sessionId,"adItemId":adItemId});
         if (response.statusCode == 200) {
           debugPrint('ad complete: ${response.data}');
           if(response.data['code'] != 200 || response.data['data'] == null) return null;
           return AdAppVo.fromJson(response.data['data']);
         }
         return null;
      } catch (e) {
        debugPrint('❌ Error fetching adComplete: $e');
        return null;
      }
  }

  static Future<AdAppVo?> adClose(String baseUrl,String platform,String packageName,String gameClientId,String sessionId,String adItemId) async {
      var url = "$baseUrl/ad/close";
      try {
         Dio dio = await DioClient().getInstance();
         final response = await dio.get(url,queryParameters:{"platform":platform,"packageName":packageName,"gameClientId":gameClientId,"sessionId":sessionId,"adItemId":adItemId});
         if (response.statusCode == 200) {
           debugPrint('ad close: ${response.data}');
           if(response.data['code'] != 200 || response.data['data'] == null) return null;
           return AdAppVo.fromJson(response.data['data']);
         }
         return null;
      } catch (e) {
        debugPrint('❌ Error fetching adClose: $e');
        return null;
      }
  }

  static Future<AdAppVo?> adClick(String baseUrl,String platform,String packageName,String gameClientId,String sessionId,String adItemId) async {
      var url = "$baseUrl/ad/click";
      try {
         Dio dio = await DioClient().getInstance();
         final response = await dio.get(url,queryParameters:{"platform":platform,"packageName":packageName,"gameClientId":gameClientId,"sessionId":sessionId,"adItemId":adItemId});
         if (response.statusCode == 200) {
           debugPrint('ad click: ${response.data}');
          if(response.data['code'] != 200 || response.data['data'] == null) return null;
           return AdAppVo.fromJson(response.data['data']);
         }
         return null;
      } catch (e) {
        debugPrint('❌ Error fetching adClick: $e');
        return null;
      } 
  }

}
